$(document).ready(function() {
	
	$(".like").live('click', function() {
		var getID = $(this).parent().attr('id').split("comment");
		var $this = $(this);
		
		$.ajax({
			url: '/likes/like/' + getID[1],
			type: 'post',
			success: function() {

				$this.removeClass();
				$this.addClass("unlike");
				$this.empty();
				$this.html("Unlike");
		
				$countID = "#likeCountComment_" + getID[1];
				
				if ( $($countID).length > 0){
					var $htmlCount = $this.next().next().html();	//htmlCount is the html text displaying like count
					$htmlCount = parseInt($htmlCount) + 1;
					
					$this.next().next().html($htmlCount);
			
				}
				else {
					$this.append('<img src="/img/thumbs_up.jpg" width="20" height="20" class="thumbsUp" id="thumbsUp_' + getID[1] + '">');
					$this.parent().append('<a class="like_count" id="likeCountComment_' + getID[1] + '">1</a>');
				}
				
			},
			error: function() {
				alert('Oops.');
			}
		}); // end ajax call
		
	}); // end .like click event
	
	
	$(".unlike").live('click', function() {
		var getID = $(this).parent().attr('id').split("comment");
		$this = $(this);
		
		$.ajax({
			url: '/likes/unlike/' + getID[1],
			type: 'post',
			success: function() {
				
				$this.removeClass();
				$this.addClass("like");
				$this.empty();
				$this.html("Like");
				
				var $htmlCount = $this.next().next().html();
				$htmlCount = parseInt($htmlCount);
				
				if ($htmlCount == 1) {
					$this.next().next().remove();
					$this.next().remove();
				}	
				else if ( $htmlCount > 1) {
					$htmlCount -= 1;
					$this.next().next().html($htmlCount);
				}
			},
			error: function() {
				alert('whoops');
			}
		}); // end ajax call
		
	}); // end .unlike click event
	
	$(".like_count").live('click', function() {
		var toAppend = '';
		$("#popup").empty();
		var split_id = $(this).attr('id').split("_");	//split id attr to get comment ID at position [1]
		
		$.getJSON('/likes/getLikeUsers/' + split_id[1], function(json){
			$.each(json.forAjax, function(key, value) {
				toAppend = '<div class="peopleWhoLikeThis"><img class="likePopUpPic" src="http://localhost/img/profile/user/' +
							value.l.user_id + '.jpg" width="75" height="75"/><a title="Show Profile" href="/users/profile/' + value.l.user_id + 
							'">' + value.u.first_name + ' ' + value.u.last_name + '</a></div><br/>';
				$("#popup").append(toAppend);
			}); // end .each
			
			$("#popup").dialog({
				title:'People Who Like This',
				draggable: false, 
				closeText: 'show',
				buttons: 
				[{
        			text: "Ok",
        			click: function() { $(this).dialog("close"); }
    			}] 
			});
		}); // end get JSON
		
		
	});
	
}); // end document ready
